import List from "../../base/Script/components/List";
import ListItem from "../../base/Script/components/ListItem";
import PopupBase from "../../base/Script/components/popups/PopupBase";
import BundleManager from "../../base/Script/core/BundleManager";
import EventManager from "../../base/Script/core/EventManager";
import ResManager from "../../base/Script/core/ResManager";
import ObjectUtil from "../../base/Script/utils/ObjectUtil";
import ClothesData from "./ccClothesData";

const { ccclass, property } = cc._decorator;

@ccclass
export default class game extends PopupBase {

    @property(List)
    listG: List = null;

    private _listData = [];
    private _curData = null;
    private _selectedId = -1;
    
    protected init(options: any): void {
        let config = ResManager.ins().getRes('config_shaonv');
        this._listData = ObjectUtil.objConvertArray(config[options.partId]);
        this.listG.numItems = this._listData.length;
        this.listG.selectedId = ClothesData.ins().getPart(options.partId);//默认选中
    }


    onListGridRender(item: cc.Node, idx: number) {
        let listItem = item.getComponent(ListItem);
        let sp = listItem.icon.getComponent(cc.Sprite);
        let url = 'spine_dingzhishaonv/'+this._listData[idx].partPath;
        this.loadRes('ChangeClothes',url, sp);
    }

    loadRes(bundle:string, url:string, sp:any){
        BundleManager.ins().loadBundle(bundle,url,(loadedResource) => {
            sp.spriteFrame = loadedResource;
        },cc.SpriteFrame);
    }

     //当列表项被选择...
     onListSelected(item: any, selectedId: number, lastSelectedId: number, val: number) {
        if (!item)
            return;
        let listItem:ListItem = item.getComponent(ListItem);
        let list: List = listItem.list;
        this._curData = this._listData[selectedId];
        if(selectedId == lastSelectedId){
            let blt = listItem.selected;
            if(blt){
                list.selectedId = -1;
                this._curData.selected = false;
            }else{
                this._curData.selected = true; 
            }
            listItem.selected = !blt;
        }else{
            listItem.selected = true;
            this._curData.selected = true;
        }
        this._selectedId = list.selectedId;
    }

    onBack(){
        this.hide();
        if(this._curData){
            ClothesData.ins().setPart(this._curData.partId,this._selectedId);
            EventManager.emit('updateSpine',this._curData);
        }
    }

    protected onHide(suspended: boolean): void {
        this.node.destroy();
    }
}